//
//  ST_ReceiveLoveCardsViewController.swift
//  btvideo
//
//  Created by mac on 2020/9/14.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyUserDefaults
import NIMSDK
import SweeterSwift

class ST_ReceiveLoveCardsViewController: UIViewController {
    
    
    func clear_data() {
        
        self.hidden_indeterminate_h_u_d()
        
        self.cards_array.removeAll()
        
        self.undoSet.removeAll()
        
        self.card_stack_view.reloadData()
        
        self.setting_personal_label(vm: nil)
        
        self.show_empty_view()
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        //        view.backgroundColor = .random
        
        //        view.addSubview(personal_sub_label)
        //
        //        personal_sub_label.snp.makeConstraints { (make) in
        //            make.centerX.equalToSuperview()
        //            make.top.equalToSuperview().offset(15)
        //        }
        //        unlike_btn.backgroundColor  = .random
        view.addSubview(unlike_btn)
        view.addSubview(like_btn)
        
        let offSet = 10
        
        unlike_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(80)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-15)
            make.right.equalTo(view.snp.centerX).offset(-offSet)
        }
        
        like_btn.snp.makeConstraints { (make) in
            make.bottom.width.height.equalTo(unlike_btn)
            make.left.equalTo(view.snp.centerX).offset(offSet)
        }
        
        view.addSubview(card_stack_view)
        card_stack_view.snp.makeConstraints { (make) in
            
            make.height.equalTo(cardHeight)
            make.left.equalToSuperview().offset(4)
            make.right.equalToSuperview().offset(-3)
            make.top.equalToSuperview().offset(9)
        }
        
        view.addSubview(ignore_btn)
        ignore_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(30)
            make.centerY.equalTo(like_btn)
            make.right.equalToSuperview().offset(-15)
        }
        
        
        
        view.addSubview(filter_btn)
        filter_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(30)
            make.centerY.equalTo(like_btn)
            make.left.equalToSuperview().offset(15)
        }
        
        
        
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(emptyView.figured_height)
            make.centerY.equalToSuperview().offset( iPhoneXSeries ? -70 : -80)
        }
        
        binding()
        
    }
    
    private func binding(){
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.refresh_data()
            }else{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
        
        NotificationCenter.default.addObserver(self, selector: #selector(showed_noti_handle(noti:)), name: Notification.Name.showedSomeOne, object: nil)
        
    }
    
    @objc fileprivate func showed_noti_handle(noti:Notification){
        
        
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController ,let id = info["id"] as? String else{
            return
        }
        
        if vc != self{
            
            self.refresh_data()
        }
    }
    //    MARK: - Request Data
    
    fileprivate var currentPage = 0
    
    /**
     当前本地未读数
     */
    fileprivate var unread_like_number = 0
    
    fileprivate func request_data(){
        
        
        currentPage += 1
        
        var param = ["page":currentPage,
                     "size":20] as [String : Any]
        
        
        self.curr_filter.conver_to_param().forEach { (item) in
            param.updateValue(item.value, forKey: item.key)
        }
        
        
        self.show_indeterminate_h_u_d()
        
        JVrequest(PH.likeIndexApi,parameters: param, success: { (json) in
            
            self.hidden_indeterminate_h_u_d()
            
            let data = json["data"]["list"]
            
            self.unread_like_number = data["count"].intValue
            
            print("收到的喜欢数据：",json)
            
            var array = [ST_PairsLoveItemViewModel]()
            
            for item in data.arrayValue{
                
                if let model = ST_PairsLoveItemViewModel.deserialize(from: item.dictionaryObject){
                    
                    let albumList = ST_PairsShareParticularModel.describe(json_array: item["album"].arrayValue)
                    
                    model.album = albumList
                    
                    array.append(model)
                }
            }
            
            
            self.cards_array = array
            
            self.card_stack_view.reloadData()
            
            self.setting_personal_label(vm: self.cards_array.first)
            
            if array.count < 1{
                self.show_empty_view()
            }else{
                self.hidden_empty_view()
            }
            
            
        }) { (code, err) in
            
            
            self.hidden_indeterminate_h_u_d()
            
            ToastHud(text: err, view: self.view)
        }
    }
    
    func refresh_data(){
        
        self.currentPage = 0
        
        self.request_data()
        
    }
    
    
    fileprivate func show_empty_view(){
        
        self.emptyView.isHidden = false
        
        self.like_btn.alpha = 0
        self.unlike_btn.alpha = 0
        self.ignore_btn.alpha = 0
        self.filter_btn.alpha = 0
    }
    
    fileprivate func hidden_empty_view(){
        
        self.emptyView.isHidden = true
        
        self.like_btn.alpha = 1
        self.unlike_btn.alpha = 1
        self.ignore_btn.alpha = 1
        self.filter_btn.alpha = 1
    }
    
    //    MARK: - Properties
    fileprivate lazy var emptyView:ST_BTEmptyView = {
        
        let control = ST_BTEmptyView.init(title: "添加我的特质，收到喜欢几率立刻增加2倍！", imageName: ST_ImageUtils.imageName("喜欢_img_喜欢(空)")!, btnTitle: "添加特质") {
            
            push_to_push_peculiarity_controller(navigationController: self.navigationController)
        }
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var card_stack_view:SwipeCardStack = {
        let control = SwipeCardStack()
        control.delegate = self
        control.dataSource = self
        control.cardStackInsets = UIEdgeInsets.zero
        return control
    }()
    
    
    fileprivate lazy var cardHeight:CGFloat = ScreenHeight-9-44-statusBarHeight-99-BTSafeAreaBottom
    
    fileprivate lazy var personal_sub_label:UILabel = {
        let control = UILabel()
        return control
    }()
    
    
    fileprivate lazy var unlike_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_不喜欢")!)
        control.add_touch_up(insideTarget: self, action: #selector(unlike_handle))
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var like_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_喜欢")!)
        control.add_touch_up(insideTarget: self, action: #selector(like_handle))
        control.alpha = 0
        return control
    }()
    
    
    //    忽略 遇见
    fileprivate lazy var ignore_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("喜欢_icon_拒绝历史")!)
        control.addTarget(self, action: #selector(push_refuse_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var filter_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_筛选")!)
        control.addTarget(self, action: #selector(filter_gender_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    private(set) var curr_filter = ST_PinterestHomeFilterModel()
    
    fileprivate lazy var love_filter:ST_PairsLoveFilterViewController = {
        
        let vc = ST_PairsLoveFilterViewController()
        
        vc.overCurrentContext = true
        
        vc.confirm_closure = {[weak self] f in
            
            self?.curr_filter = f
            self?.refresh_data()
            
        }
        
        return vc
        
    }()
    
    fileprivate lazy var love_filter_navigation_controller:UINavigationController = {
        
        let vc =  UINavigationController.create_hiding_bar_navigation_controller(rootViewController: love_filter)
        
        vc.overCurrentContext = true
        
        return vc
    }()
    
    fileprivate lazy var cards_array = [ST_PairsLoveItemViewModel]()
    
    fileprivate lazy var undoSet = Set<String>()
    
}

extension ST_ReceiveLoveCardsViewController{
    
    fileprivate func setting_personal_label(vm:ST_PairsLoveItemViewModel?){
        
        guard let model = vm else{
            personal_sub_label.attributedText = NSAttributedString()
            return
        }
        
        var str = "他"
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == ST_SEX.male{
            str = "她"
        }
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        if model.send_way == 1{
            str += "从推荐喜欢了你哦！"
            let attrString = NSMutableAttributedString(string: str)
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
            
            personal_sub_label.attributedText = attrString
            
        }else if model.send_way == 2{
            str += "喜欢你 " + model.feature_name + " 的特质哦！"
            
            let attrString = NSMutableAttributedString(string: str)
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: 5))
            
            let attr2: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 1, green: 0.76, blue: 0.03, alpha: 1)]
            
            attrString.addAttributes(attr2, range: NSRange(location: 5, length: model.feature_name.count))
            
            attrString.addAttributes(attr, range: NSRange(location: 5+model.feature_name.count, length: 6))
            
            personal_sub_label.attributedText = attrString
        }else{
            personal_sub_label.attributedText = NSAttributedString()
        }
        
    }
    
}

//MARK: - Event
extension ST_ReceiveLoveCardsViewController{
    
    @objc func unlike_handle(){
        
        
        card_stack_view.swipe(SwipeDirection.left, animated: true)
        
    }
    @objc func like_handle(){
        
        card_stack_view.swipe(SwipeDirection.right, animated: true)
        
    }
    
    @objc func push_refuse_handle(){
        
        self.navigationController?.pushViewController(ST_RefuseLoveViewController())
        
    }
    
    @objc func filter_gender_handle(sender:UIButton){
        
        
        GlobalPresent(toController: self.love_filter_navigation_controller)
        
    }
}

//MARK: - Delegate
extension ST_ReceiveLoveCardsViewController:SwipeCardStackDelegate, SwipeCardStackDataSource{
    
    /*
     func card(didBeginSwipe card: SwipeCard) {
     
     }
     
     func card(didCancelSwipe card: SwipeCard) {
     
     }
     
     func card(didContinueSwipe card: SwipeCard) {
     
     }
     
     func card(didSwipe card: SwipeCard, with direction: SwipeDirection) {
     
     
     print("动画问题 ：",self.card_stack_view.isAnimating)
     }
     
     func card(didTap card: SwipeCard) {
     
     }
     */
    
    
    
    
    func cardStack(_ cardStack: SwipeCardStack, didUndoCardAt index: Int, from direction: SwipeDirection) {
        
        if direction == .left{
            
            guard let m =  self.cards_array[safe:index] else {
                return
            }
            
            let vc = BTVerticalAlertViewController.createReceivedPropAlert(model: m)
            
            vc.confirm_closure = {[weak self] in
                
                self?.card_stack_view.swipe(.right, animated: true)
                
            }
            
            vc.cancel_closure = {[weak self] in
                
                self?.card_stack_view.swipe(.left, animated: true)
                
            }
            
            GlobalPresent(toController: vc)
            
        }
        
    }
    
    func cardStack(_ cardStack: SwipeCardStack, didSwipeCardAt index: Int, with direction: SwipeDirection) {
        
        guard let m =  self.cards_array[safe:index] else {
            return
        }
        
        //        不喜欢 使用道具的人 提示
        if m.props_integral > 0 && !undoSet.contains(m.accid) && direction == .left{
            
            undoSet.update(with: m.accid)
            
            //            print("动画问题 ：",cardStack.isAnimating)
            
            cardStack.undoLastSwipe(animated: true)
            
            return
        }
        
        self.swipeIndex(index: index, direction: direction)
        
        
    }
    
    fileprivate func swipeIndex(index:Int,direction: SwipeDirection){
        
        if card_stack_view.topCardIndex == nil{
            self.show_empty_view()
        }
        
        /*
         if let i = cardStack.topCardIndex , let m = self.cards_array[safe:i]{
         self.setting_personal_label(vm: m)
         }else{
         self.setting_personal_label(vm: nil)
         }*/
        
        guard let m =  self.cards_array[safe:index] else {
            return
        }
        
        var action = true
        //        不喜欢
        if direction == .left{
            action = false
        }
        
        let avatar = m.album.first?.imageUrl ?? ""
        
        PairsLikeAction(info: ST_MatchUserInfo.init(accid: m.accid, avatar: avatar, nickname: m.nickname), likeAction: action, isReceive: true, fromVC: self) { (code, err, matched) in
            
            if code == 1{
                
                matched?()
                
                
            }else {
                
                if let e = err{ self.toast(text: e) }
                
            }
        }
        
    }
    
    
    func cardStack(_ cardStack: SwipeCardStack, cardForIndexAt index: Int) -> SwipeCard {
        
        let card = SwipeCard()
        
        card.swipeDirections = [.left, .right]
        for direction in card.swipeDirections {
            card.setOverlay(ST_TinderCardOverlay(direction: direction), forDirection: direction)
        }
        
        //        card.delegate = self
        
        
        let itemView = ST_AIRecommendCardView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth - 8, height: cardHeight)))
        
        let model = cards_array[index]
        
        itemView.bind_view_data_set(model: model)
        
        card.content = itemView
        
        return card
        
    }
    
    func numberOfCards(in cardStack: SwipeCardStack) -> Int {
        return cards_array.count
    }
    
    
    
    
}
